package com.bobo.demo.Thread.sync;

import lombok.Data;

public class UnsafeBank {

    public static void main(String[] args) {
        Account account = new Account(100,"结婚基金");//账户

        DrawingMoney drawingMoney1 = new DrawingMoney(account,50,"你");
        DrawingMoney drawingMoney2 = new DrawingMoney(account,100,"girlFriend");

        drawingMoney1.start();
        drawingMoney2.start();

    }


}

class DrawingMoney  extends Thread {

    private Account account;

    private long drawingMoney;//取了多少钱

    private long nowMoney;//现在有多少钱

    public DrawingMoney(Account account, Integer drawingMoney, String name) {
        super(name);
        this.account = account;
        this.drawingMoney = drawingMoney;
    }

    @Override
    public void run() {
        draw();
    }

    void draw(){
        if(account.getBalance() - drawingMoney <= 0.00) {
            System.out.println(Thread.currentThread().getName()+"余额不足，无法取钱!");
            return;
        }

        //sleep可以放大问题的发生性
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        //卡内余额
        account.setBalance(account.getBalance() - drawingMoney);


        //你手里的钱
        nowMoney = nowMoney + drawingMoney;

        System.out.println(account.getCardCode()+"余额为："+account.getBalance());

        System.out.println(this.getName()+"手里的钱"+nowMoney);

    }
}

//账户
@Data
class Account{

    //余额
    private long balance;

    private String cardCode;

    public Account(long balance, String cardCode) {
        this.balance = balance;
        this.cardCode = cardCode;
    }
}